package com.cby.code.helper;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

import java.lang.ref.WeakReference;

/**
 * @description: SpinnerHelper
 * @author: ChenBaoYang
 * @createDate: 2022/3/21 10:07 上午
 */
public class SpinnerHelper<T, V> {

    protected Context context;
    protected WeakReference<Spinner> spinnerWeakReference;
    protected T[] keys;
    protected V[] values;
    protected SharedPreferences mSp;
    protected String name;

    public SpinnerHelper(Context context, String name) {
        this.context = context.getApplicationContext();
        mSp = this.context.getSharedPreferences("sdk_sp", Context.MODE_PRIVATE);
        this.name = name;
    }

    public void bind(Spinner spinner) {
        spinnerWeakReference = new WeakReference<>(spinner);
        initSpinnerData();
    }

    public void setKeys(T[] ts) {
        this.keys = ts;
    }

    public void setValues(V[] vs) {
        this.values = vs;
    }

    private void initSpinnerData() {
        Spinner spinner = spinnerWeakReference.get();
        if(spinner == null) {
            return;
        }
        ArrayAdapter<T> adapter = new ArrayAdapter<T>(context, android.R.layout.simple_spinner_item, keys);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);

        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
                Log.d("chenby", "Set as " + keys[pos]);
                save(pos);
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
            }
        });

        // 这里设置默认方向为横屏，SDK内部的默认方向也是
        spinner.setSelection(mSp.getInt(name, 0));
    }

    public void save(int pos) {
        mSp.edit().putInt(name, pos).commit();
    }

    public V get() {
        int pos = mSp.getInt(name, 0);
        if (pos < 0 || pos > 3) {
            pos = 0;
        }
        return values[pos];
    }
}
